package com.tools.web.interceptor.auth._common;

import com.tools.common.object.Note;
import com.tools.common.object.json.JsonKit;
import com.tools.common.thread.Timeunit;
import com.tools.web.interceptor.auth.*;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * RedisTemplate&lt;String, String&gt; 客户端操作 Redis 实现的 “用户单在线记录” 的 AuthenticationManager 身份认证拦截器
 * */
@Note("RedisTemplate<String, String> 客户端操作 Redis 实现的 “用户单在线记录” 的 AuthenticationManager 身份认证拦截器")
public abstract class RedisTemplateSingleAuthenticationManager extends GenericAuthenticationManager implements SingleRedisLuaScript {

    @Note("操作 Redis 的 RedisTemplate<String, String> 客户端")
    private final RedisTemplate<String, String> redisTemplate;

    protected RedisTemplateSingleAuthenticationManager(RedisTemplate<String, String> redisTemplate, AuthSource source, AuthUserService authUserService) {
        super(source, authUserService);
        this.redisTemplate = Objects.requireNonNull(redisTemplate, "操作 Redis 的 RedisTemplate<String, String> 客户端为 null");
    }

    @Override
    public final Timeunit getTimeunitUsedBySubclass() {
        return Timeunit.SECOND;
    }

    @Override
    protected GetAuthUserResult getAuthUser(String key, AuthToken decryptedAuthToken) {
        String json = this.redisTemplate.opsForValue().get(key);
        if(json != null) {
            SingleAuthUser authUser = JsonKit.toEntity(json, SingleAuthUser.class);
            boolean b1 = Objects.equals(authUser.getLoginDeviceType(), decryptedAuthToken.getLoginDeviceType());
            boolean b2 = Objects.equals(authUser.getUuid(), decryptedAuthToken.getUuid());
            if(b1 && b2) {
                return new GetAuthUserResult(true, authUser);
            }
            return new GetAuthUserResult(false, null);
        }
        return super.protected_getResultIfExpired(decryptedAuthToken);
    }


    @Override
    protected void setAuthUser(String key, AuthUser srcAuthUser, AuthToken decryptedAuthToken) {
        SingleAuthUser authUser = (SingleAuthUser) srcAuthUser;
        authUser.setLoginDeviceType(decryptedAuthToken.getLoginDeviceType());
        authUser.setLoginUserType(decryptedAuthToken.getLoginUserType());
        authUser.setUuid(decryptedAuthToken.getUuid());
        String json = JsonKit.toJSON(authUser);
        long expiration = this.getTimeunitUsedBySubclass().cast(decryptedAuthToken.getExpirationMill(), Timeunit.MILL);
        this.redisTemplate.opsForValue().set(key, json, expiration, TimeUnit.SECONDS);
    }


    @Override
    protected void removeAuthUser(String key) {
        this.redisTemplate.delete(key);
    }

    @Override
    protected void updateAuthUser(String key, AuthUser authUser) {
        String json = this.redisTemplate.opsForValue().get(key);
        if(json == null) return;
        SingleAuthUser oldAuthUser = JsonKit.toEntity(json, SingleAuthUser.class);
        Object user = authUser.getUser();
        oldAuthUser.setUser(user);
        authUser.copyCustomData(oldAuthUser);
        authUser.copyAuthData(oldAuthUser);
        String newJson = JsonKit.toJSON(authUser);
        this.redisTemplate.execute((RedisConnection connection) -> connection.eval(
                UPDATE_AUTH_USER.getBytes(),
                ReturnType.INTEGER,
                0,
                key.getBytes(),
                newJson.getBytes()
        ));
    }

    @Override
    protected void protected_loginOut(String key, String loginDeviceType, String uuid) {
        this.removeAuthUser(key);
    }
}
